package com.vincce.sport.controller;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.entity.City;
import com.vincce.sport.entity.Page;
import com.vincce.sport.entity.School;
import com.vincce.sport.entity.SysUser;
import com.vincce.sport.entity.Team;
import com.vincce.sport.entity.Zone;
import com.vincce.sport.mapper.CityMapper;
import com.vincce.sport.mapper.SchoolMapper;
import com.vincce.sport.mapper.TeamMapper;
import com.vincce.sport.mapper.ZoneMapper;

@Controller
@RequestMapping("/team")
public class TeamController extends BaseController{


	@Resource
	private SchoolMapper schoolMapper;
	@Resource
	private TeamMapper teamMapper;
	@Resource
	private ZoneMapper zoneMapper;
	@Resource
	private CityMapper cityMapper;

	/**
	 * 分页查询
	 * @param model
	 * @param page
	 * @param team
	 * @return
	 */
	@RequestMapping("/teamList")
	public String queryTeamByPage(Model model,Page<Team> page,Team team){
		Map<String, Object> filter = new HashMap<String, Object>();
		
		if(team.getName() != null && !team.getName().equals("")){
	            filter.put("name", team.getName());
	    }
		if(team.getSchoolId() != null && !team.getSchoolId().equals("")){
            filter.put("schoolId", team.getSchoolId());
        }
		//数据权限过滤
		model.addAttribute("role",0);

		SysUser user = getCurrentUser();
		if(user!=null){

            if(user.getRoleId()==2){
                if(user.getTeamId()!=null){
                    filter.put("id", user.getTeamId());
                    model.addAttribute("role",2);
                }
            }

		}
		
		page.setFilter(filter);
		page.setTotal(teamMapper.queryTeamByCount(page.getFilter()));
		page.setResult(replace(teamMapper.queryTeamByPage(page)));
		
		model.addAttribute("schoolList",schoolMapper.queryBySchoolAll());
		model.addAttribute("team",team);
		model.addAttribute("page",page);
		return "/backstage/teamList";
	}
	
	@RequestMapping("/teamWebList")
	public String teamWebList(Model model,Integer schoolId,Integer zoneId){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("schoolId", schoolId);
		List<Zone> zoneList=zoneMapper.queryByZoneAll();
		List<Team> teamList=teamMapper.queryTeamBySchoolId(map);
		List<School> schoolList = schoolMapper.querySchoolById(map);
		map.put("zoneId", zoneId);
		List<City> list= cityMapper.queryCityByZoneId(map); 
		
		List<School> schools =schoolMapper.querySchoolByMap(map);
		if (zoneId==null) {
			model.addAttribute("cityName","请选择");
			model.addAttribute("schoolName","请选择");
		}
		else if(zoneId!=null){
			model.addAttribute("cityName",list.get(0).getName());
			model.addAttribute("schoolName",schools.get(0).getName());
		}
		model.addAttribute("zoneId",zoneId);
		model.addAttribute("list",list);
		
		Team team = new Team();
		if (schoolList!=null && schoolList.size()>0) {
			model.addAttribute("schoolId",schoolList.get(0).getId());
			
			for (School school:schoolList) {
				team.setSchoolId(school.getId());
				int i=1;
				map.put("schoolId", school.getId());
				List<Team> teamList1=teamMapper.queryTeamBySchoolId(map);
				/*for (Team t:teamList1) {
					t.setId(i);
					i++;
					
					
				}*/
				school.setTeamList(teamList1);
			}
		}
		
		model.addAttribute("zoneList",zoneList);
		model.addAttribute("teamList",teamList);
		//model.addAttribute("schoolId",schoolId);
		model.addAttribute("schoolList",schoolList);
		//model.addAttribute("school",school);
		//model.addAttribute("first",first);
		return "/foreground/team";
	}
	
	/**
	 * 图片路径替换
	 * @param imgStorageList
	 * @return
	 */
	public List<Team> replace(List<Team> imgTempList){
		if(imgTempList!=null && imgTempList.size()>0){
			for(Team itl:imgTempList){
				itl.setLogUrl(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+itl.getLogUrl(), "ori"));
			}
		}
		return imgTempList;
	}
	
	/**
	 * 新增
	 * @param model
	 * @param team
	 * @return
	 */
//	@RequestMapping("/addTeam")
//	@ResponseBody
//	public String addTeam(Model model,Team team){
//		Boolean flag=false;
//		team.setCreateUser(getCurrentUser().getId().intValue());
//		team.setCreateTime(new Date());
//		team.setUpdateTime(new Date());
//		team.setUpdateUser(getCurrentUser().getId().intValue());
//		Long count=teamMapper.insertTeam(team);
//		flag=count>0?true:false;
//		Map<String, Object> result = new HashMap<String, Object>();
//		result.put("suc", flag);
//        return JSON.toJSONString(result);
//	}
	
	/**
	 * 修改
	 * @param model
	 * @param school
	 * @return
	 */
//	@RequestMapping("/updateTeam")
//	@ResponseBody
//	public String updateTeam(Model model,Team team){
//		Boolean flag=false;
//		team.setUpdateTime(new Date());
//		team.setUpdateUser(1);
//		Long count=teamMapper.updateTeam(team);
//		flag=count>0?true:false;
//		Map<String, Object> result = new HashMap<String, Object>();
//		result.put("suc", flag);
//        return JSON.toJSONString(result);
//	}
	
	
	/**
	 * 根据ID删除
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping("/deleteById")
	@ResponseBody
	public String deleteById(Model model,Integer id){
		Boolean flag=false;
		Integer count=teamMapper.deleteById(id);
		flag=count>0?true:false;
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("suc", flag);
        return JSON.toJSONString(result);
	}
	
	/**
	 * 新增修改
	 * @param model
	 * @param file
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/addOrUpdateTeam")
	@ResponseBody
	public String addOrUpdateTeam(Model model,Team team, @RequestParam(value = "file", required = false) List<MultipartFile> file,
            HttpServletRequest request) throws IOException{
		Long count=0L;
		
		
        Map<String, Object> result = new HashMap<String, Object>();
        SimpleStorageClient.StorageResult obj = new SimpleStorageClient.StorageResult(200, "");
        SimpleStorageClient.StorageResult obj2 = new SimpleStorageClient.StorageResult(200, "");
        if(CheckUtil.isEmpty(team.getId())){
        	if (file != null && !file.isEmpty() && file.size()>1) {
        		
        		
                String fileName = file.get(0).getOriginalFilename();
                
                String fileName2 = file.get(1).getOriginalFilename();
                String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                String fileType2 = fileName2.substring(fileName2.lastIndexOf("."), fileName2.length());

                
                if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")
                		&&!fileType2.equals(".jpg") && !fileType2.equals(".JPG") && !fileType2.equals(".png") && !fileType2.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
                } else {
                    obj = SimpleStorageClient.upload(2, file.get(0).getInputStream(), fileType);
                    obj2 = SimpleStorageClient.upload(2, file.get(1).getInputStream(), fileType2);
                    if (obj.statusCode == 200 && obj2.statusCode == 200) {
                    	String path = obj.info.replaceAll("\\\\", "/");
                    	String path2 = obj2.info.replaceAll("\\\\", "/");
                    	//result.put("img", String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+path, "ori"));
                    	//result.put("imgPath", path);
                    	team.setLogUrl(path);
                    	team.setLogUrl2(path2);
                    	team.setCreateUser(getCurrentUser().getId().intValue());
                		team.setCreateTime(new Date());
                		team.setUpdateTime(new Date());
                		team.setUpdateUser(getCurrentUser().getId().intValue());
                    	count=teamMapper.insertTeam(team);
                    	
                    }
                }
            } else{
            	result.put("msg","请选择文件,宽图和窄图都要上传!");
                result.put("suc", false);
            }
        	
        	
        }else{
        	
        	if (file != null && !file.isEmpty()) {
            	String fileName = file.get(0).getOriginalFilename();
            	String fileName2 = file.get(1).getOriginalFilename();
            	String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
                String fileType2 = fileName2.substring(fileName2.lastIndexOf("."), fileName2.length());

            	if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")
            			&&!fileType2.equals(".jpg") && !fileType2.equals(".JPG") && !fileType2.equals(".png") && !fileType2.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
				}else{
					obj = SimpleStorageClient.upload(2, file.get(0).getInputStream(), fileType);
                    obj2 = SimpleStorageClient.upload(2, file.get(1).getInputStream(), fileType2);
					if (obj.statusCode == 200 && obj2.statusCode == 200) {
	                	String path= obj.info.replaceAll("\\\\", "/");
	                	String path2 = obj2.info.replaceAll("\\\\", "/");
	                	team.setLogUrl(path);
	                	team.setLogUrl2(path2);
	                	team.setUpdateTime(new Date());
	                	team.setUpdateUser(getCurrentUser().getId().intValue());
	                	count = teamMapper.updateTeam(team);
	                }
				}
            } else {
            	team.setUpdateTime(new Date());
            	team.setUpdateUser(getCurrentUser().getId().intValue());
            	count = teamMapper.updateTeam(team);
            }
        }
        
        result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
	}

	@RequestMapping("/queryFrontTeamBySchoolId")
	@ResponseBody
	public String queryFrontTeamBySchoolId(Model model,Integer schoolId){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("schoolId", schoolId);
		//数据权限过滤
		SysUser user = getCurrentUser();
		/*if(user!=null){
			if(user.getTeamId()!=null){
				map.put("teamId", user.getTeamId());
			}
		}*/
        if(user!=null){

            if(user.getRoleId()==2){
                if(user.getTeamId()!=null){
                    map.put("teamId", user.getTeamId());
                }
            }

        }
		List<Team> list=teamMapper.queryTeamBySchoolId(map);
        return JSON.toJSONString(list);
	}
	@RequestMapping("/queryTeamBySchoolId")
	@ResponseBody
	public String queryTeamBySchoolId(Model model,Integer schoolId){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("schoolId", schoolId);
		//数据权限过滤
		SysUser user = getCurrentUser();
		if(user!=null){
            if(user.getRoleId()==2){
                if(user.getTeamId()!=null){
                    map.put("teamId", user.getTeamId());
                }
            }
		}
		List<Team> list=teamMapper.queryTeamBySchoolId(map);
		return JSON.toJSONString(list);
	}
}
